package com.yyx.jupiter.service.recommend.rerank;

import com.alibaba.fastjson2.JSONObject;
import com.yyx.jupiter.conf.PropertyConfig;
import com.yyx.jupiter.entity.RecomReq;
import com.yyx.jupiter.entity.RecomVideo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@Service
public class RerankManager {

    @Resource
    PropertyConfig propertyConfig;

    @Resource
    ExposeFilterRerank exposeFilterRerank;

    @Resource
    ThompsonSampleRerank thompsonSampleRerank;

    private List<Rerankable<RecomVideo>> getRerankStrategies(RecomReq recomReq) throws Exception {
        List<Rerankable<RecomVideo>> rerankStrategyList = new LinkedList<>();
        String strategy = recomReq.getStrategy();
        JSONObject strategyJson = propertyConfig.getStrategy().getJSONObject(strategy);
        String rerankPriority = strategyJson.getString("rerankPriority");
        String[] rerankNames = rerankPriority.split(",");
        for (String rerankName : rerankNames) {
            switch (rerankName) {
                case "exposeFilter":
                    rerankStrategyList.add(exposeFilterRerank);
                    break;
                case "thompsonSample":
                    rerankStrategyList.add(thompsonSampleRerank);
                    break;
            }
        }
        return rerankStrategyList;
    }

    public List<RecomVideo> getRerankItemList(RecomReq recomReq, List<RecomVideo> recomVideos) throws Exception {
        long startTime = System.currentTimeMillis();

        // 获取重排列表
        List<Rerankable<RecomVideo>> rerankStrategyList = getRerankStrategies(recomReq);

        // 串行请求重排
        for (Rerankable<RecomVideo> rerankStrategy : rerankStrategyList) {
            recomVideos = rerankStrategy.rerank(recomVideos, recomReq);
        }

        log.info("requestId:{}, rerank elapsed: {} ms, rerank size:{}",
                recomReq.getRequestId(), (System.currentTimeMillis() - startTime), recomVideos.size());
        return recomVideos;
    }
}
